/* File.cpp
Copyright (c) 2008 Michael Zahniser
Please note the license terms (MIT license) at the end of this document.

Function definitions for the File class.
*/

#include "File.h"

#include <fstream>

using std::ifstream;
using std::ofstream;



File::File()
{
}



File::File(const string &path)
{
	Open(path);
}



// Open a file. Return true if successful.
bool File::Open(const string &path)
{
	clear();

	this->path = path;
	ifstream in(path.c_str());

	// Find out how big the file is.
	in.seekg(0, std::ios_base::end);
	size_t size = in.tellg();
	in.seekg(0, std::ios_base::beg);

	if(!in || !size)
		return false;
	
	// Read the file into a temporary buffer, then copy it to this string.
	char *buffer = new char[size];
	in.read(buffer, size);
	assign(buffer, size);
	delete [] buffer;
	
	return true;
}



// Save the file, either saving over the file it was loaded from, or
// saving to a new path if one is given.
bool File::Save() const
{
	return Save(path);
}



// Save the file to a new path.
bool File::Save(const string &path) const
{
	this->path = path;
	
	ofstream out(path.c_str());
	if(!out)
		return false;
	
	out.write(c_str(), size());
	
	return true;
}



// Back up the file (save "<file name.ext>~").
bool File::Backup() const
{
	if(rename(path.c_str(), (path + '~').c_str()) != 0)
		return false;
	
	return true;
}



/* Copyright (c) 2008 Michael Zahniser

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE. */

